<?php
namespace Resources\model;

 use Zend\Db\ResultSet\ResultSet;
 use Zend\Db\TableGateway\TableGateway;
 use Zend\Db\Sql\Select;
 use Zend\Paginator\Adapter\DbSelect;
 use Zend\Paginator\Paginator;

class AdditionalTable
{
    protected $tableGateway;
    
    function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway=$tableGateway;
    }
    
    public function getAdditional($id)
    {
        $rowset = $this->tableGateway->select(array('ID' => $id));
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row $id");
        }
        return $row;
    }
    
    public function fetchAll($paginated=false)
    {
        if ($paginated) {
            
            $select = new Select('resource');
            $resultSetPrototype = new ResultSet();
            $resultSetPrototype->setArrayObjectPrototype(new Additional());
            
            $paginatorAdapter = new DbSelect(
                $select,
                $this->tableGateway->getAdapter(),
                $resultSetPrototype
            );
            $paginator = new Paginator($paginatorAdapter);
            return $paginator;
        }
        $resultSet = $this->tableGateway->select();
        return $resultSet;
    }  
    
    public function saveAdditional(Additional $additional,$type)
    {
        $data = array(
            'ID' => $additional->ID,
            'TITLE' => $additional->TITLE,
            'DURATION' => $additional->DURATION,
            'REMARK'  => $additional->REMARK
        );
        $id =$additional->ID;
        if ($type == 0) {
            $this->tableGateway->insert($data);
        } elseif($type==1) {
            if ($this->getAdditional($id)) {
                $this->tableGateway->update($data, array('ID' => $id));
            } else {
                throw new \Exception('Additional ID does not exist');
            }
        }
    }
}

?>